package com.kaochong.xcx.service.impl;

import com.kaochong.xcx.cache.FormIdCache;
import com.kaochong.xcx.cache.FriendHelpCache;
import com.kaochong.xcx.cache.WordBookCache;
import com.kaochong.xcx.common.constant.CommonConstant;
import com.kaochong.xcx.enums.FinishStatus;
import com.kaochong.xcx.enums.ResultEnum;
import com.kaochong.xcx.exception.KaoChongException;
import com.kaochong.xcx.entity.FriendsHelp;
import com.kaochong.xcx.entity.User;
import com.kaochong.xcx.entity.UserInfo;
import com.kaochong.xcx.entity.WordBook;
import com.kaochong.xcx.pojo.model.FriendHelpTemplate;
import com.kaochong.xcx.dao.FriendsHelpMapper;
import com.kaochong.xcx.service.ShareService;
import com.kaochong.xcx.service.UserService;
import com.kaochong.xcx.utils.DateUtil;
import com.kaochong.xcx.web.aspect.CurrentUser;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

/**
 * 分享给好友解锁业务类
 * @author han
 * @date 2018-06-25 11:56
 */
@Service
@Slf4j
public class ShareServiceImpl implements ShareService {
	
	@Autowired
	FriendsHelpMapper friendsHelpMapper;
	
	@Autowired
	UserService userService;
	
	@Autowired
	WechatServiceImpl wechatService;
	
	@Autowired
	FormIdCache formIdCache;
	
	@Autowired
	FriendHelpCache friendHelpCache;
	
	@Autowired
	WordBookCache wordBookCache;
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void friendHelp(CurrentUser currentUser, String openId, Integer target, Integer stage) {
		WordBook wordBook = wordBookCache.getByTarget(target);
		if (null == wordBook) {
			log.error("【背单词-好友助力】target error");
			throw new KaoChongException(ResultEnum.TARGET_CHOOSE_ERROR);
		}
		Long userId = currentUser.getId();
		
		Integer count1 = friendHelpCount(openId, target, stage);
		if (count1 >= CommonConstant.FRIEND_HELP_COUNT) {
			//throw new KaoChongException(ResultEnum.HELP_FRIEND_SUCCESS_ERROR);
			log.info("【背单词-好友助力】friend already unlock success");
			return;
		}
		
		User user = userService.findByOpenId(openId);
		if (null == user) {
			throw new KaoChongException(ResultEnum.HELP_FRIEND_OPENID_ERROR);
		}
		
		if (user.getId().equals(userId)) {
			throw new KaoChongException(ResultEnum.HELP_FRIEND_OWN_ERROR);
		}
		
		boolean exists = friendHelpCache.hExists(userId);
		if (exists) {
			log.info("【背单词-好友助力】redis user already exist");
			return;
		}
		
		UserInfo userInfo = userService.findUserInfo(user.getId(), target);
		if (null == userInfo || !stage.equals(userInfo.getCurrStage())
				|| FinishStatus.FINISHED.getCode().equals(userInfo.getFinishStatus())) {
			log.error("【背单词-好友助力】stage error, form stage={}, real={}", stage, userInfo.getCurrStage());
			return;
		}
		
		Integer c = friendHelpCache.hPut(userId, openId);
		if (c == 1) {
			FriendsHelp help = new FriendsHelp();
			help.setUserId(userId);
			help.setOpenId(openId);
			help.setStatus(0);
			help.setTarget(target);
			help.setStage(stage);
			help.setCreateTime(new Date());
			friendsHelpMapper.insert(help);
			
			Map<String,Object> map = new HashMap<>();
			map.put("nickname", currentUser.getNickname());
			map.put("portrait", currentUser.getPortrait());
			friendHelpCache.lLeftPush(openId, target, stage, map);
		}
		
		if(count1 == (CommonConstant.FRIEND_HELP_COUNT - 1)) {
			// 发模板消息
			String formId = formIdCache.getValidFormId(openId);
			if (StringUtils.isNotBlank(formId)) {
				FriendHelpTemplate template = new FriendHelpTemplate();
				template.setOpenId(openId);
				template.setFormId(formId);
				template.setKeyword1(DateUtil.getCurrent());
				template.setKeyword2(CommonConstant.FRIEND_HELP_KEYWORD2);
				wechatService.sendLockSuccessTemplate(template);
			}
		}
	}
	
	@Override
	public List<Map<String,Object>> friendHelpList(String openId, Integer target, Integer stage) {
		List<Map<String, Object>> maps = friendHelpCache.friendHelpList(openId, target, stage);
		return maps;
	}
	
	@Override
	public Integer friendHelpCount(String openId, Integer target, Integer stage) {
		Long length = friendHelpCache.length(openId, target, stage);
		return length.intValue();
	}
	
	@Override
	public Integer resetFriendHelp(String openId, Integer target) {
		Integer count = friendsHelpMapper.resetFriendHelp(openId, target);
		return count;
	}
}
